<?php
namespace App\Model;

use App\Lib\CacheKey;
use App\Model\BaseModel;
use App\Service\BotsService;

/**
 * 机器人相关
 * BotsModel.php
 * @author zhouqiang
 * @date 2018/05/02
 */
class BotsModel extends BaseModel 
{
	protected $table = 'bots';

	protected $primaryKey = 'bot_id';

	public static $activeMap = [
		'yes' => 1, // 激活
		'no' => 0, // 未激活
	];

	public static $statusMap = [
		'yes' => 1, // 已登录
		'no' => 0, // 未登录
	];

	public static $stopMap = [
		'yes' => 1, // 关闭
		'no' => 0, // 未关闭
	];

    public static $loginStatusMap = [
        'login'=>1,
        'default'=>0,
    ];

    public static $fromMap = [
        'yes' => 1, // 允许
        'no' => 2, // 不允许
    ];

    public static $botTypeMap = [
        'item' => 1, // 饰品机器人
        'money' => 2, // steam钱包充值机器人
    ];

	/**
	 * 获取机器人信息
	 * @param  int $botId 机器人ID
	 * @return array
	 */
	public static function getBotsInfoBybotId($botId)
	{
		$where = array(
			'is_active' => self::$activeMap['yes'],
			'is_stop' => self::$stopMap['no'],
			'bot_id' => $botId,
			'client_no' => env('APP_NO'),
		);

		$result = static::where($where)->first();

		return $result ? $result->toArray() : [];
	}

	/**
	 * 获取所有机器人信息
	 * @param  int $botId 机器人ID
	 * @return array
	 */
	public static function getBotsInfoByAll($botId = NULL)
	{
		$where = array(
			'is_active' => self::$activeMap['yes'],
			'is_stop' => self::$stopMap['no'],
			'client_no' => env('APP_NO'),
            'bot_type' => self::$botTypeMap['item'],
		);

		if ($botId) {
			$where['bot_id'] = $botId;
		}

		$result = static::where($where)->get();

		return $result ? $result->toArray() : [];
	}

    /**
     * 根据条件获取收货机器人 limit 10
     * @param $condition
     * @return mixed
     */
	public static function getLivingBotsByWhere($condition, $limit = 10)
    {
        return static::where($condition)->orderBy('last_login_time', 'desc')->limit($limit)->get();
    }

	/**
	 * 修改机器人登录信息
	 * @param  int $botId 机器人ID
	 * @return array
	 */
	public static function updateBotsLogin($botId)
	{
		$where = array(
			'is_active' => self::$activeMap['yes'],
			'is_stop' => self::$stopMap['no'],
			'bot_id' => $botId,
			'client_no' => env('APP_NO'),
		);

		$field = array(
			'last_login_time' => date('Y-m-d H:i:s', time()),
			'login_status' => self::$statusMap['yes'],
		);

		return static::where($where)->update($field);
	}

	/**
	 * 获取最早登录机器人
	 * @param  int $botId 机器人ID
	 * @return array
	 */
	public static function getBotsByEarlyLogin($botId = NULL)
	{
		$where = array(
			'is_active' => self::$activeMap['yes'],
			'is_stop' => self::$stopMap['no'],
			'client_no' => env('APP_NO'),
		);

		if ($botId) {
			$where['bot_id'] = $botId;
		}

		$result = static::where($where)->orderBy('last_login_time')->first();

		return $result ? $result->toArray() : [];
	}

	/**
	 * 获取所有登录机器人信息
	 * @param  int $botId 机器人ID
	 * @return array
	 */
	public static function getBotsLoginByAll($botId = NULL)
	{
		$where = array(
			'login_status' => self::$statusMap['yes'],
			'is_active' => self::$activeMap['yes'],
			'is_stop' => self::$stopMap['no'],
			'client_no' => env('APP_NO'),
		);

		if ($botId) {
			$where['bot_id'] = $botId;
		}

		$result = static::where($where)->orderBy('last_login_time', 'desc')->get();

		return $result ? $result->toArray() : [];
	}

	/**
	 * 修改机器人登录状态
	 * @param  int $botId 机器人ID
	 * @return array
	 */
	public static function updateBotsLoginState($botId)
	{
		$where = array(
			'bot_id' => $botId,
		);

		$field = array(
			'login_status' => self::$statusMap['no'],
		);

		return static::where($where)->update($field);
	}

	/**
	 * 获取机器人库存信息
	 * @param  int $botId 机器人ID
	 * @return array
	 */
	public static function getBotsInvByAll($botId)
	{
		$where = array(

		);

		if ($botId) {
			$where['bot_id'] = $botId;
		}

		$result = static::selectRaw('bot_id,client_no,steam_id')->where($where)->get();

		return $result ? $result->toArray() : [];
	}

	/**
	 * 获取机器人库存
	 * @param  int $botId 机器人ID
	 * @return array
	 */
	public static function getBotsInvByBotId($botId)
	{
		$where = array(
			'bot_id' => $botId,
		);

		$result = static::selectRaw('bot_id,dota_invs,csgo_invs')->where($where)->first();

		return $result ? $result->toArray() : [];
	}

	/**
	 * 修改机器人库存
	 * @param  int $botId 机器人ID
	 * @param  int $csgoInvs csgo库存
	 * @param  int $dotaInvs dota库存
	 * @return bool
	 */
	public static function updateBotsInvByBotId($botId, $csgoInvs = NULL, $dotaInvs = NULL)
	{
		$where = array(
			'bot_id' => $botId,
		);

		$field = [];
		if ($csgoInvs) {
			$field['csgo_invs'] = $csgoInvs;

			if ($csgoInvs >= 950) {
				$field['can_from'] = self::$fromMap['no'];
			}
		}

		return static::where($where)->update($field);
	}

    /**
     * 获取数据库中全部可存入机器人
     * @return array
     */
    public static function getFromAllLivingBotLists()
    {
        $condition['login_status'] = static::$loginStatusMap['login'];
        $condition['is_active'] = static::$activeMap['yes'];
        $condition['can_from'] = static::$fromMap['yes'];
        $condition['is_stop'] = static::$stopMap['no'];
        $canFromBotList = static::where($condition)->where('client_no', '<>', 'die')->selectRaw('*, CONCAT("laravel:' . CacheKey::BOT_LIST_PRE . '", steam_account) as str_steam_account')->orderBy('last_login_time', 'desc')->get();

        if (empty($canFromBotList)) {
            return [];
        }

        $canFromBotList = $canFromBotList->toArray();
        if (empty($canFromBotList)) {
            return [];
        }

        return $canFromBotList;
    }

    /**
     * 获取redis中全部机器人
     * @return mixed
     */
    public static function getResdisAllLivingBotLists()
    {
        $redis = app('redis');
        $res = $redis->keys('laravel:' . CacheKey::BOT_LIST_PRE . '*');
        return $res;
    }

    /**
     * 通过steam_account获取机器人
     * @return array
     */
    public static function getLivingBotBySteamAccount($botSteamAccount)
    {
        $condition['login_status'] = static::$loginStatusMap['login'];
        $condition['is_active'] = static::$activeMap['yes'];
        $condition['is_stop'] = static::$stopMap['no'];
        $condition['can_from'] = static::$fromMap['yes'];
        $condition['steam_account'] = $botSteamAccount;
        $botLiving = static::where($condition)->where('client_no', '<>', 'die')->first();
        if (empty($botLiving)) {
            return [];
        }

        $botLiving = $botLiving->toArray();
        if (empty($botLiving)) {
            return [];
        }

//        $botLiving['steam'] = LoginService::getInstance()->getBot($botLiving['steam_account']);
        return $botLiving;
    }

    /**
     * 通过id获取机器人
     * @return array
     */
    public static function getLivingBotByBotId($botId)
    {
        //获取当前机器的机器人
        $condition['client_no'] = getenv('APP_NO');
        if(empty($condition['client_no'])){
            return [];
        }
        $condition['login_status'] = static::$loginStatusMap['login'];
        $condition['is_active'] = static::$activeMap['yes'];
        $condition['is_stop'] = static::$stopMap['no'];
        $condition['can_from'] = static::$fromMap['yes'];
        $condition['bot_id'] = $botId;
        $botLiving = static::where($condition)->where('client_no', '<>', 'die')->first();
        if (empty($botLiving)) {
            return [];
        }

        $botLiving = $botLiving->toArray();
        if (empty($botLiving)) {
            return [];
        }

        $botLiving['steam'] = BotsService::getInstance()->getRobotCache($botLiving['steam_account']);
        return $botLiving;
    }

    /**
     * 获取检测交易链接的机器人
     * @return bool
     */
    public static function getCheckTradeUrlLivingBot()
    {

        //获取当前机器的机器人
        $condition['client_no'] = getenv('APP_NO');
        if(empty($condition['client_no'])){
            return false;
        }

        $condition['login_status'] = static::$loginStatusMap['login'];
        $condition['is_active'] = static::$activeMap['yes'];
        $condition['is_stop'] = static::$stopMap['no'];
        $canFromBotList = static::selectRaw('bot_id,client_no,steam_id,steam_account,bot_name,can_from,can_out')->where($condition)->orderBy('last_login_time', 'desc')->limit(10)->get();
        if (empty($canFromBotList)) {
            return false;
        }

        $canFromBotList = $canFromBotList->toArray();
        if (empty($canFromBotList)) {
            return false;
        }
        shuffle($canFromBotList);
        $rand = array_rand($canFromBotList);
        $botLiving = $canFromBotList[$rand];

        $botLiving['steam'] = BotsService::getInstance()->getRobotCache($botLiving['steam_account']);
        return $botLiving;
    }

    public static function getOneBotSettings($botId)
    {
        $bot = static::find($botId);
        if (empty($bot)) {
            return false;
        }
        return [
            'id' => $bot['id'],
            'botId' => $bot['steam_account'],
            'username' => $bot['steam_account'],
            'password' => $bot['password'],
            'apiKey' => $bot['apikey'],
            'mobileAuth' => [
                "sharedSecret" => $bot['shared_secret'],
                "identitySecret" => $bot['identity_secret'],
                "deviceId" => "android:" . preg_replace('/^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12}).*$/', '$1-$2-$3-$4-$5', md5($bot['steam_id']))
            ]
        ];
    }
    /**
     * 获取机器人信息
     * @param  int $botId 机器人ID
     * @return array
     */
    public static function getFromBotsInfoBybotId($botId)
    {
        $condition['client_no'] = getenv('APP_NO');
        if(empty($condition['client_no'])){
            return [];
        }
        $condition['login_status'] = static::$loginStatusMap['login'];
        $condition['is_active'] = static::$activeMap['yes'];
        $condition['is_stop'] = static::$stopMap['no'];
        $condition['can_from'] = static::$fromMap['yes'];
        $condition['bot_id'] = $botId;
        $botLiving = static::where($condition)->where('client_no', '<>', 'die')->first();
        if (empty($botLiving)) {
            return [];
        }

        $botLiving = $botLiving->toArray();
        if (empty($botLiving)) {
            return [];
        }

        $botLiving['steam'] = BotsService::getInstance()->getRobotCache($botLiving['steam_account']);
        return $botLiving;
    }

	/**
	 * 修改机器人登录时间
	 * @param  int $botId 机器人ID
	 * @return bool
	 */
    public static function updateLastLoginTime($botId)
    {
    	$where = array(
    		'bot_id' => $botId,
    	);

    	$field = array(
    		'last_login_time' => date('Y-m-d H:i:s', time()),
    	);

    	return static::where($where)->update($field);
    }

    /**
     * 获取steam钱包充值机器人信息
     * @param  int $botId 机器人ID
     * @return array
     */
    public static function getWalletcodeBotsInfoBybotId($botId)
    {
        $condition['client_no'] = getenv('APP_NO');
        if(empty($condition['client_no'])){
            return [];
        }
        $condition['is_active'] = static::$activeMap['yes'];
        $condition['is_stop'] = static::$stopMap['no'];
        $condition['bot_id'] = $botId;
        $botLiving = static::where($condition)->where('client_no', '<>', 'die')->first();
        if (empty($botLiving)) {
            return [];
        }

        $botLiving = $botLiving->toArray();
        if (empty($botLiving)) {
            return [];
        }

        $botLiving['steam'] = BotsService::getInstance()->getRobotCache($botLiving['steam_account']);
        $botLiving['steampowered'] = BotsService::getInstance()->getSteampoweredRobotCache($botLiving['steam_account']);
        return $botLiving;
    }

    /**
     * 获取steam钱包充值机器人信息
     * @return array|bool
     */
    public static function getWalletcodeBotsInfo()
    {
        $condition['client_no'] = getenv('APP_NO');
        if(empty($condition['client_no'])){
            return [];
        }
        $condition['is_active'] = static::$activeMap['yes'];
        $condition['is_stop'] = static::$stopMap['no'];
        $condition['bot_type'] = static::$botTypeMap['money'];
        $botList = static::where($condition)->where('client_no', '<>', 'die')->orderBy('last_login_time', 'desc')->limit(10)->get();
        if (empty($botList)) {
            return false;
        }

        $botList = $botList->toArray();
        if (empty($botList)) {
            return false;
        }
        shuffle($botList);
        $rand = array_rand($botList);
        $botLiving = $botList[$rand];

        $botLiving['steampowered'] = BotsService::getInstance()->getSteampoweredRobotCache($botLiving['steam_account']);
        return $botLiving;
    }
}